#include <QtCore>

#include "XmlGenerator.h"
typedef cblp::XmlGenerator XML;

#include "RoModule.h"

#include "DirComponent.h"


int main(int argc, char * argv[])
{
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));

    QCoreApplication app(argc, argv);

    QPointer<RoModule> module = new RoModule(&app);
    QPointer<DirComponent> component = new DirComponent(module);

    QObject::connect(module, SIGNAL( error(QAbstractSocket::SocketError) ),
                     &app, SLOT( quit() ));

    module->connectToNetwork("localhost");

    return app.exec();
}


DirComponent::DirComponent(RoModule * module):
    super(module)
{
    setName("dir");

    methods["ls"]["description"] = "Lists files in a directory.";
    methods["ls"]["example"] = "<path>path to a directory</path>";
}


RoComponent::RoMethodResult DirComponent::ro_ls(RoIqStanza request, QDomDocument * answer)
{
    QDomDocument argument = request.argument();
    QString claimant = request.from();
    RoStanzaId rid = request.id();

    RoIqStanza badParamsError = RoIqStanza::createError(RoIqStanza::BadParameters, claimant, rid);

    if ( argument.documentElement().tagName() != "path" )
    {
        badParamsError.setErrorDescription("Argument must be <path>path to a directory</path>");
        *answer = badParamsError;
        return FinishedWithError;
    }

    QString path = argument.documentElement().text();

    if ( path.isEmpty() )
    {
        badParamsError.setErrorDescription("<path/> is empty");
        *answer = badParamsError;
        return FinishedWithError;
    }

    QDir dir(path);
    if ( not dir.exists() )
    {
        badParamsError.setErrorDescription("path doesn't lead to a directory");
        *answer = badParamsError;
        return FinishedWithError;
    }

    RoIqStanza datum;
    foreach ( QFileInfo fi, dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System) )
    {
        datum = RoIqStanza::createDatum(claimant, rid, "fileinfo")
                .setBodyText(fi.fileName());

        if ( fi.isSymLink() )
            datum.setBodyAttribute("symlink", "true");

        if ( fi.isDir() )
            datum.setBodyAttribute("dir", "true");
        else
            datum.setBodyAttribute("size", QString::number(fi.size()));

        sendStanza(datum);
    }

    *answer = XML("ok").toDocument();
    return FinishedSuccessfully;
}
